﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using contactusform.dataaccess;
using contactusform.services;
using Recaptcha.Web;
using Recaptcha.Web.Mvc;
using System.Threading.Tasks;


namespace contactusform.web.Controllers
{
    [AllowAnonymous]
    public class ContactController : Controller
    {
        private ContactService _contactService;

        /// <summary>
        /// Index Action On Contact Controller
        /// </summary>
        /// <returns>Contact Form View</returns>
        public ActionResult Index()
        {
            return View(new ContactViewModel());
        }

        /// <summary>
        /// ActionMethod for form submission
        /// </summary>
        /// <param name="contactViewModel">ContactViewModel containing contact form info</param>
        /// <returns>Redirect to Index Action or ModelStateErrors on failure</returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> ContactInfoSubmission(ContactViewModel contactViewModel)
        {
            #region Captcha

            var recaptchaHelper = this.GetRecaptchaVerificationHelper();

            if (String.IsNullOrEmpty(recaptchaHelper.Response))
            {
                ModelState.AddModelError("", "Captcha answer cannot be empty.");
                return View("Index", contactViewModel);
            }

            var recaptchaResult = await recaptchaHelper.VerifyRecaptchaResponseTaskAsync();

            if (recaptchaResult != RecaptchaVerificationResult.Success)
            {
                ModelState.AddModelError("", "Incorrect captcha answer.");
            }

            #endregion

            else
            {
                if (!ModelState.IsValid)
                    return View("Index", contactViewModel);

                if (contactViewModel.BestTimeToCall != null && !UtilitiesHelper.IsValidDateTimeToCall(contactViewModel.BestTimeToCall.Value))
                {
                    ModelState.AddModelError("", "The best time to call can't be a past date and has to be between 9:00 AM and 6:00 PM in 15 minutes increment");
                    return View("Index", contactViewModel);
                }

                _contactService = new ContactService();

                var contactInfo = MappingHelper.Map<ContactViewModel, Contact>(contactViewModel);
                var saved = _contactService.SaveContactInfo(contactInfo);

                if (saved)
                    return RedirectToAction("Index");

                ModelState.AddModelError("", "Ups! Something went wrong, please try again");
            }

            return View("Index", contactViewModel);

        }

    }

}